package library.and.xps.com.step.view.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.jude.utils.JUtils;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnClickListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.squareup.okhttp.Request;
import com.zhy.autolayout.AutoFrameLayout;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import library.and.xps.com.step.EventBusCommond;
import library.and.xps.com.step.R;
import library.and.xps.com.step.URLConstants;
import library.and.xps.com.step.m.model.CreateTeamParam;
import library.and.xps.com.step.m.netapi.OkHttpClientUtils;
import library.and.xps.com.step.net.ResponceWrapper;
import library.and.xps.com.step.util.RequestCallback;
import library.and.xps.com.step.view.activity.CityChooseActivity;
import library.and.xps.com.step.view.activity.OrgTypeChooseActivity;
import library.and.xps.com.step.view.base.BaseFragment;
import library.and.xps.com.step.view.customview.WheelView;

import static library.and.xps.com.step.view.activity.CityChooseActivity.RESPONCE_CITY;
import static library.and.xps.com.step.view.activity.OrgTypeChooseActivity.RESPONCE_ORG_TYPE;


public class CreateTeamInfoFragment extends BaseFragment implements TakePhoto.TakeResultListener, InvokeListener ,OnClickListener {
    private AutoFrameLayout frame_img;
    private ImageView iv_team_sign;
    private Button bt_goahead;
    private EditText et_team_name, et_org_name, et_org_desc;
    private TextView et_org_district, et_org_scale, et_org_type;
    private View anchor;
    private String UPLOAD_ORG_SIGN = "UPLOAD_orgZATION_SIGN";//上传图片FLAG
    private CreateTeamParam createTeamParam = new CreateTeamParam();

    ArrayList<String> teamScalevalues = new ArrayList<>();
    ArrayList<String> teamTypevalues = new ArrayList<>();
    private InvokeParam invokeParam;
    private File file;//已选择的文件
    private TakePhoto takePhoto;
    Uri imageUri;
    WheelView wheelViewPlan;
    public static final int CHOOSE_CITY = 0;
    public static final int CHOOSE_ORG_TYPE = 1;

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getRes() {
        return R.layout.fragment_create_team_info;
    }

    @Override
    protected void init(View view) {
        frame_img = r2v(view, R.id.frame_img);
        frame_img.setOnClickListener(this);
        iv_team_sign = r2v(view, R.id.iv_img);
        bt_goahead = r2v(view, R.id.bt_goahead);
        et_org_scale = r2v(view, R.id.et_org_scale);
        et_org_scale.setOnClickListener(this);
        bt_goahead.setOnClickListener(this);
        et_team_name = r2v(view, R.id.et_team_name);
        et_org_name = r2v(view, R.id.et_org_name);
        et_org_type = r2v(view, R.id.et_org_type);
        et_org_type.setOnClickListener(this);
        et_org_district = r2v(view, R.id.et_org_district);
        et_org_district.setOnClickListener(this);
        et_org_desc = r2v(view, R.id.et_org_desc);
        anchor = r2v(view, R.id.anchor);

        teamScalevalues.add("0-100人");
        teamScalevalues.add("100人-500人");
        teamScalevalues.add("500人-1000人");
        teamScalevalues.add("1000人-5000人");
        teamScalevalues.add("5000人-10000人");
        teamScalevalues.add("10000人以上");

        teamTypevalues.add("政府/事业单位");
        teamTypevalues.add("IT行业");
        teamTypevalues.add("金融行业");
        teamTypevalues.add("专业服务");
        teamTypevalues.add("文化传媒行业");
        teamTypevalues.add("建筑/房地产");
        teamTypevalues.add("其他组织");
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void setData(View view) {

    }

    public void hide() {
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.hide(this);
        fragmentTransaction.commit();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) return;
        if (requestCode == CHOOSE_CITY) {
            String city = data.getStringExtra(RESPONCE_CITY);
            et_org_district.setText(city);
        } else if (requestCode == CHOOSE_ORG_TYPE) {
            int type = data.getIntExtra(RESPONCE_ORG_TYPE, 0);
            et_org_type.setText(teamTypevalues.get(type));
            createTeamParam.setType(++type + "");//avoiding type is 0
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.frame_img:
                File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
                imageUri = Uri.fromFile(file);

                CompressConfig config = new CompressConfig.Builder()
                        .setMaxSize(102400)
                        .create();
                takePhoto.onEnableCompress(config, false);
                CropOptions.Builder builder = new CropOptions.Builder();
                builder.setAspectX(800).setAspectY(800);
                builder.setOutputX(800).setOutputY(800);
                builder.setWithOwnCrop(true);
                takePhoto.onPickFromGalleryWithCrop(imageUri, builder.create());
                break;

            case R.id.bt_goahead:
                if (ableContinue()) {
                    createTeamParam.setTname(et_team_name.getText().toString());
                    createTeamParam.setEnterprise(et_org_name.getText().toString());
                    if (getUser() != null)
                        createTeamParam.setCreater(getUser().getUserid());
                    else break;
                    createTeamParam.setAddress(et_org_district.getText().toString());
                    createTeamParam.setDescription(et_org_desc.getText().toString());
                    EventBus.getDefault().post(createTeamParam);
                    EventBus.getDefault().post(EventBusCommond.Create_TeamPassFragment);
                }

                break;

            case R.id.et_org_district:
                startActivityForResult(new Intent(getActivity(), CityChooseActivity.class), CHOOSE_CITY);
                break;
            case R.id.et_org_scale:
                showDialogChooseOrgScale();
                break;
            case R.id.et_org_type:
                startActivityForResult(new Intent(getActivity(), OrgTypeChooseActivity.class), CHOOSE_ORG_TYPE);
                break;
        }
    }

    void upload(final File file) {
        final File[] files = {file};
        final String[] filenames = {"file_upload"};
        try {
            OkHttpClientUtils.postUploadFilesAsync(getActivity(), URLConstants.FILE.FileUpload, files, filenames, new RequestCallback() {
                @Override
                public void onFailure(Request request, Exception e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(ResponceWrapper response) {
                    if (response.getResponcecode() == 200) {
                        createTeamParam.setMark(response.getBody());

                        Glide.with(getActivity()).load(file)
                                .placeholder(R.mipmap.ic_empty_data)
                                .bitmapTransform(new RoundedCornersTransformation(getActivity(), 10, 0, RoundedCornersTransformation.CornerType.ALL))
                                .into(iv_team_sign);

                        frame_img.setBackground(null);
                    }
                }

                @Override
                public void onStart() {

                }
            }, UPLOAD_ORG_SIGN);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    void showDialogChooseOrgScale() {
        ViewHolder contentViewHolder = new ViewHolder(getActivity().getLayoutInflater().inflate(R.layout.dialog_choose_org_scale, null));
        View contentView = contentViewHolder.getInflatedView();
        wheelViewPlan = (WheelView) contentView.findViewById(R.id.main_wv);
        wheelViewPlan.setOffset(1);

        wheelViewPlan.setItems(teamScalevalues);


        ViewHolder headerViewHolder = new ViewHolder(getActivity().getLayoutInflater().inflate(R.layout.header, null));
        View headerView = headerViewHolder.getInflatedView();
        ((TextView) headerView.findViewById(R.id.tv_hint)).setText("选择企业规模:");

        ViewHolder footerViewHolder = new ViewHolder(getActivity().getLayoutInflater().inflate(R.layout.footer, null));
        View footerView = footerViewHolder.getInflatedView();
        footerView.findViewById(R.id.al_footer).setBackgroundColor(Color.parseColor("#f4f4f4"));

        DialogPlus dialog = DialogPlus.newDialog(getActivity())
                .setContentHolder(contentViewHolder)
                .setGravity(Gravity.CENTER)
                .setFooter(footerView)
                .setHeader(headerView)
                .setOnClickListener(this)
                .setInAnimation(R.anim.dialog_in_anim)
                .setOutAnimation(R.anim.dialog_out_anim)
                .create();

        dialog.show();
    }

    boolean ableContinue() {
        if (getUser() == null) {
            JUtils.Toast("错误");
        } else if (TextUtils.isEmpty(et_team_name.getText().toString())) {
            Snackbar.make(anchor, "请填写团队名", Snackbar.LENGTH_LONG)
                    .setAction("确定", null).show();
            return false;
        } else if (TextUtils.isEmpty(et_org_name.getText().toString())) {
            Snackbar.make(anchor, "请填写企业名", Snackbar.LENGTH_LONG)
                    .setAction("确定", null).show();
            return false;
        } else if (TextUtils.isEmpty(et_org_district.getText().toString())) {
            Snackbar.make(anchor, "请填写地址", Snackbar.LENGTH_LONG)
                    .setAction("确定", null).show();
            return false;
        } else if (createTeamParam.getType().equals("0")) {
            Snackbar.make(anchor, "请选择企业类型", Snackbar.LENGTH_LONG)
                    .setAction("确定", null).show();
            return false;
        } else if (createTeamParam.getScale() == 0) {
            Snackbar.make(anchor, "请选择企业规模", Snackbar.LENGTH_LONG)
                    .setAction("确定", null).show();
            return false;
        } else if (TextUtils.isEmpty(et_org_desc.getText().toString())) {
            Snackbar.make(anchor, "请填写描述", Snackbar.LENGTH_LONG)
                    .setAction("确定", null).show();
            return false;
        }

        return true;
    }
    @Override
    public void takeSuccess(TResult result) {
        TImage t = result.getImage();
        file = new File(t.getOriginalPath());
        upload(file);
    }

    @Override
    public void takeFail(TResult result, String msg) {
        JUtils.Toast(msg);
    }

    @Override
    public void takeCancel() {
        JUtils.Log("选择取消");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(getActivity(), type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onClick(DialogPlus dialog, View view) {
        dialog.dismiss();
        switch (view.getId()) {
            case R.id.footer_close_button:

                break;
            case R.id.footer_confirm_button:
                createTeamParam.setScale(wheelViewPlan.getSeletedIndex() + 1);
                et_org_scale.setText(wheelViewPlan.getSeletedItem() + "");
                break;
        }
    }
}
